/**
 * Historico de alteração
 *
 * Data         Autor   Descrição
 * 24/10/2010   Jerry   Criação do cabeçalho.
 *
 */

package railbee.banco.jdbc;

import java.sql.Connection;
import java.util.Collection;
import org.apache.log4j.Logger;

import railbee.banco.dao.*;
import railbee.banco.dto.*;
import railbee.banco.exceptions.*;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class ServidoresDaoImpl extends AbstractDAO implements ServidoresDao
{
	/** 
	 * The factory class for this DAO has two versions of the create() method - one that
takes no arguments and one that takes a Connection argument. If the Connection version
is chosen then the connection will be stored in this attribute and will be used by all
calls to this DAO, otherwise a new Connection will be allocated for each operation.
	 */
	protected java.sql.Connection userConn;

	protected static final Logger logger = Logger.getLogger( ServidoresDaoImpl.class );

	private String nomeTabela;
	protected final String SQL_INSERT;
	protected final String SQL_SELECT;
	
	public ServidoresDaoImpl(final java.sql.Connection userConn)
	{
		this.userConn = userConn;
		//this.nomeTabela = nomeTabela;
		/** 
		 * SQL INSERT statement for this table
		 */
		SQL_INSERT = "INSERT INTO " + getTableName() + " ( sigla_estacao, porta_servidor, ip_servidor ) VALUES ( ?, ?, ? )";
		/** 
		 * All finder methods in this class use this SELECT constant to build their queries
		 */
		SQL_SELECT = "SELECT sigla_estacao, porta_servidor, ip_servidor FROM " + getTableName() + "";

	}
	
	//protected String SQL_INSERT = "INSERT INTO " + getTableName() + " ( sigla_estacao, porta_servidor, ip_servidor ) VALUES ( ?, ?, ? )";
	
	/** 
	 * Finder methods will pass this value to the JDBC setMaxRows method
	 */
	protected int maxRows;

	
	

	/** 
	 * SQL UPDATE statement for this table
	 */
	protected final String SQL_UPDATE = "UPDATE " + getTableName() + " SET sigla_estacao = ?, porta_servidor = ?, ip_servidor = ? WHERE sigla_estacao = ?";

	/** 
	 * SQL DELETE statement for this table
	 */
	protected final String SQL_DELETE = "DELETE FROM " + getTableName() + " WHERE sigla_estacao = ?";

	/** 
	 * Index of column sigla_estacao
	 */
	protected static final int COLUMN_SIGLA_ESTACAO = 1;

	/** 
	 * Index of column porta_servidor
	 */
	protected static final int COLUMN_PORTA_SERVIDOR = 2;

	/** 
	 * Index of column ip_servidor
	 */
	protected static final int COLUMN_IP_SERVIDOR = 3;

	/** 
	 * Number of columns
	 */
	protected static final int NUMBER_OF_COLUMNS = 3;

	/** 
	 * Index of primary-key column sigla_estacao
	 */
	protected static final int PK_COLUMN_SIGLA_ESTACAO = 1;

	/** 
	 * Inserts a new row in the servidores table.
	 */
	public ServidoresPk insert(Servidores dto) throws ServidoresDaoException
	{
		long t1 = System.currentTimeMillis();
		// declare variables
		final boolean isConnSupplied = (userConn != null);
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			// get the user-specified connection or get a connection from the ResourceManager
			conn = isConnSupplied ? userConn : ResourceManager.getConnection();
		
			stmt = conn.prepareStatement( SQL_INSERT );
			int index = 1;
			stmt.setString( index++, dto.getSiglaEstacao() );
			stmt.setInt( index++, dto.getPortaServidor() );
			stmt.setString( index++, dto.getIpServidor() );
			if (logger.isDebugEnabled()) {
				logger.debug( "Executing " + SQL_INSERT + " with DTO: " + dto);
			}
		
			int rows = stmt.executeUpdate();
			long t2 = System.currentTimeMillis();
			if (logger.isDebugEnabled()) {
				logger.debug( rows + " rows affected (" + (t2-t1) + " ms)");
			}
		
			reset(dto);
			return dto.createPk();
		}
		catch (Exception _e) {
			logger.error( "Exception: " + _e.getMessage(), _e );
			throw new ServidoresDaoException( "Exception: " + _e.getMessage(), _e );
		}
		finally {
			ResourceManager.close(stmt);
			if (!isConnSupplied) {
				ResourceManager.close(conn);
			}
		
		}
		
	}

	/** 
	 * Updates a single row in the servidores table.
	 */
	public void update(ServidoresPk pk, Servidores dto) throws ServidoresDaoException
	{
		long t1 = System.currentTimeMillis();
		// declare variables
		final boolean isConnSupplied = (userConn != null);
		Connection conn = null;
		PreparedStatement stmt = null;
		
		try {
			// get the user-specified connection or get a connection from the ResourceManager
			conn = isConnSupplied ? userConn : ResourceManager.getConnection();
		
			if (logger.isDebugEnabled()) {
				logger.debug( "Executing " + SQL_UPDATE + " with DTO: " + dto);
			}
		
			stmt = conn.prepareStatement( SQL_UPDATE );
			int index=1;
			stmt.setString( index++, dto.getSiglaEstacao() );
			stmt.setInt( index++, dto.getPortaServidor() );
			stmt.setString( index++, dto.getIpServidor() );
			stmt.setString( 4, pk.getSiglaEstacao() );
			int rows = stmt.executeUpdate();
			reset(dto);
			long t2 = System.currentTimeMillis();
			if (logger.isDebugEnabled()) {
				logger.debug( rows + " rows affected (" + (t2-t1) + " ms)");
			}
		
		}
		catch (Exception _e) {
			logger.error( "Exception: " + _e.getMessage(), _e );
			throw new ServidoresDaoException( "Exception: " + _e.getMessage(), _e );
		}
		finally {
			ResourceManager.close(stmt);
			if (!isConnSupplied) {
				ResourceManager.close(conn);
			}
		
		}
		
	}

	/** 
	 * Deletes a single row in the servidores table.
	 */
	public void delete(ServidoresPk pk) throws ServidoresDaoException
	{
		long t1 = System.currentTimeMillis();
		// declare variables
		final boolean isConnSupplied = (userConn != null);
		Connection conn = null;
		PreparedStatement stmt = null;
		
		try {
			// get the user-specified connection or get a connection from the ResourceManager
			conn = isConnSupplied ? userConn : ResourceManager.getConnection();
		
			if (logger.isDebugEnabled()) {
				logger.debug( "Executing " + SQL_DELETE + " with PK: " + pk);
			}
		
			stmt = conn.prepareStatement( SQL_DELETE );
			stmt.setString( 1, pk.getSiglaEstacao() );
			int rows = stmt.executeUpdate();
			long t2 = System.currentTimeMillis();
			if (logger.isDebugEnabled()) {
				logger.debug( rows + " rows affected (" + (t2-t1) + " ms)");
			}
		
		}
		catch (Exception _e) {
			logger.error( "Exception: " + _e.getMessage(), _e );
			throw new ServidoresDaoException( "Exception: " + _e.getMessage(), _e );
		}
		finally {
			ResourceManager.close(stmt);
			if (!isConnSupplied) {
				ResourceManager.close(conn);
			}
		
		}
		
	}

	/** 
	 * Returns the rows from the servidores table that matches the specified primary-key value.
	 */
	public Servidores findByPrimaryKey(ServidoresPk pk) throws ServidoresDaoException
	{
		return findByPrimaryKey( pk.getSiglaEstacao() );
	}

	/** 
	 * Returns all rows from the servidores table that match the criteria 'sigla_estacao = :siglaEstacao'.
	 */
	public Servidores findByPrimaryKey(String siglaEstacao) throws ServidoresDaoException
	{
		Servidores ret[] = findByDynamicSelect( SQL_SELECT + " WHERE sigla_estacao = ?", new Object[] { siglaEstacao } );
		return ret.length==0 ? null : ret[0];
	}

	/** 
	 * Returns all rows from the servidores table that match the criteria ''.
	 */
	public Servidores[] findAll() throws ServidoresDaoException
	{
		return findByDynamicSelect( SQL_SELECT + " ORDER BY sigla_estacao", null );
	}

	/** 
	 * Returns all rows from the servidores table that match the criteria 'sigla_estacao = :siglaEstacao'.
	 */
	public Servidores[] findWhereSiglaEstacaoEquals(String siglaEstacao) throws ServidoresDaoException
	{
		return findByDynamicSelect( SQL_SELECT + " WHERE sigla_estacao = ? ORDER BY sigla_estacao", new Object[] { siglaEstacao } );
	}

	/** 
	 * Returns all rows from the servidores table that match the criteria 'porta_servidor = :portaServidor'.
	 */
	public Servidores[] findWherePortaServidorEquals(int portaServidor) throws ServidoresDaoException
	{
		return findByDynamicSelect( SQL_SELECT + " WHERE porta_servidor = ? ORDER BY porta_servidor", new Object[] {  new Integer(portaServidor) } );
	}

	/** 
	 * Returns all rows from the servidores table that match the criteria 'ip_servidor = :ipServidor'.
	 */
	public Servidores[] findWhereIpServidorEquals(String ipServidor) throws ServidoresDaoException
	{
		return findByDynamicSelect( SQL_SELECT + " WHERE ip_servidor = ? ORDER BY ip_servidor", new Object[] { ipServidor } );
	}

//	public ServidoresDaoImpl(String nomeTabela)
//	{
//		this.nomeTabela = nomeTabela;
//	}

	/**
	 * Method 'ServidoresDaoImpl'
	 * 
	 * @param userConn
	 */
	

	/** 
	 * Sets the value of maxRows
	 */
	public void setMaxRows(int maxRows)
	{
		this.maxRows = maxRows;
	}

	/** 
	 * Gets the value of maxRows
	 */
	public int getMaxRows()
	{
		return maxRows;
	}

	/**
	 * Method 'getTableName'
	 * 
	 * @return String
	 */
	public String getTableName()
	{
		return "railbee.public.servidores";
		//return "railbee.public.servidores";
		//return this.nomeTabela;
	}

	/** 
	 * Fetches a single row from the result set
	 */
	protected Servidores fetchSingleResult(ResultSet rs) throws SQLException
	{
		if (rs.next()) {
			Servidores dto = new Servidores();
			populateDto( dto, rs);
			return dto;
		} else {
			return null;
		}
		
	}

	/** 
	 * Fetches multiple rows from the result set
	 */
	protected Servidores[] fetchMultiResults(ResultSet rs) throws SQLException
	{
		Collection resultList = new ArrayList();
		while (rs.next()) {
			Servidores dto = new Servidores();
			populateDto( dto, rs);
			resultList.add( dto );
		}
		
		Servidores ret[] = new Servidores[ resultList.size() ];
		resultList.toArray( ret );
		return ret;
	}

	/** 
	 * Populates a DTO with data from a ResultSet
	 */
	protected void populateDto(Servidores dto, ResultSet rs) throws SQLException
	{
		dto.setSiglaEstacao( rs.getString( COLUMN_SIGLA_ESTACAO ) );
		dto.setPortaServidor( rs.getInt( COLUMN_PORTA_SERVIDOR ) );
		dto.setIpServidor( rs.getString( COLUMN_IP_SERVIDOR ) );
	}

	/** 
	 * Resets the modified attributes in the DTO
	 */
	protected void reset(Servidores dto)
	{
	}

	/** 
	 * Returns all rows from the servidores table that match the specified arbitrary SQL statement
	 */
	public Servidores[] findByDynamicSelect(String sql, Object[] sqlParams) throws ServidoresDaoException
	{
		// declare variables
		final boolean isConnSupplied = (userConn != null);
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			// get the user-specified connection or get a connection from the ResourceManager
			conn = isConnSupplied ? userConn : ResourceManager.getConnection();
		
			// construct the SQL statement
			final String SQL = sql;
		
		
			if (logger.isDebugEnabled()) {
				logger.debug( "Executing " + SQL);
			}
		
			// prepare statement
			stmt = conn.prepareStatement( SQL );
			stmt.setMaxRows( maxRows );
		
			// bind parameters
			for (int i=0; sqlParams!=null && i<sqlParams.length; i++ ) {
				stmt.setObject( i+1, sqlParams[i] );
			}
		
		
			rs = stmt.executeQuery();
		
			// fetch the results
			return fetchMultiResults(rs);
		}
		catch (Exception _e) {
			logger.error( "Exception: " + _e.getMessage(), _e );
			throw new ServidoresDaoException( "Exception: " + _e.getMessage(), _e );
		}
		finally {
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			if (!isConnSupplied) {
				ResourceManager.close(conn);
			}
		
		}
		
	}

	/** 
	 * Returns all rows from the servidores table that match the specified arbitrary SQL statement
	 */
	public Servidores[] findByDynamicWhere(String sql, Object[] sqlParams) throws ServidoresDaoException
	{
		// declare variables
		final boolean isConnSupplied = (userConn != null);
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			// get the user-specified connection or get a connection from the ResourceManager
			conn = isConnSupplied ? userConn : ResourceManager.getConnection();
		
			// construct the SQL statement
			final String SQL = SQL_SELECT + " WHERE " + sql;
		
		
			if (logger.isDebugEnabled()) {
				logger.debug( "Executing " + SQL);
			}
		
			// prepare statement
			stmt = conn.prepareStatement( SQL );
			stmt.setMaxRows( maxRows );
		
			// bind parameters
			for (int i=0; sqlParams!=null && i<sqlParams.length; i++ ) {
				stmt.setObject( i+1, sqlParams[i] );
			}
		
		
			rs = stmt.executeQuery();
		
			// fetch the results
			return fetchMultiResults(rs);
		}
		catch (Exception _e) {
			logger.error( "Exception: " + _e.getMessage(), _e );
			throw new ServidoresDaoException( "Exception: " + _e.getMessage(), _e );
		}
		finally {
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			if (!isConnSupplied) {
				ResourceManager.close(conn);
			}
		
		}
		
	}

	@Override
	public void setNomeTabela(String nomeTabela) {
		this.nomeTabela  = nomeTabela;
		
	}

}
